package com.rico.gallery.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import com.rico.gallery.device.DeviceInfo;
import com.rico.gallery.message.IMessage;
import com.rico.gallery.message.ImageMessage;
import com.rico.gallery.message.UserLoginMessage;
import com.rico.gallery.message.MessageType;
import com.rico.gallery.message.MsgMessage;
import com.rico.gallery.socket.MessageHandler;
import com.rico.gallery.socket.ServerConnectionManager;
import com.rico.gallery.socket.SocketConnection;
import com.rico.gallery.utils.Constant;
import com.rico.gallery.utils.FileUtils;
import com.rico.gallery.utils.MD5Util;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class GalleryService extends Service implements MessageHandler{

    private static String TAG="GalleryService";

    private ServerSocket serverSocket;

    private int port=10088;

    private HashMap<SocketConnection,User> socketConnectionMap=new HashMap<>();

    private List<MessageHandler> messageHandlerList=new ArrayList<>();

    private SharedPreferences sharedPreferences;


    @Override
    public IBinder onBind(Intent intent) {
        initService();
        return new MyBinder();
    }
    private void initService(){
        try {
            serverSocket=new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        Socket socket = serverSocket.accept();
                        SocketConnection socketThread=new SocketConnection(socket);
                        User user=new User(socketThread);
                        socketConnectionMap.put(socketThread,user);
                        socketThread.setMessageHandler(GalleryService.this);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        sharedPreferences = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE);
        new Thread(new ConnectServerThread()).start();
    }


    public void addMessageHandler(MessageHandler messageHandler){
        messageHandlerList.add(messageHandler);
    }


    @Override
    public void onMessageReceived(SocketConnection socketThread, IMessage message) {
        for(MessageHandler item:messageHandlerList){
            item.onMessageReceived(socketThread,message);
        }
        boolean b=true;
       // boolean b=checkPermission(this.socketConnectionMap.get(socketThread),message);
        if(!b){
            MsgMessage successMessage=new MsgMessage(MessageType.NOT_LOGIN,"未登陆！");
            try {
                socketThread.sendMessage(successMessage);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        switch (message.getMessageType()){
            case LOGIN:
                long startTime=System.currentTimeMillis();
                doLogin(socketThread,message);
                long endTime=System.currentTimeMillis();
                System.out.println("endTime-startTime : "+(endTime-startTime));
                break;
            case IMAGE:
                doImage(socketThread, message);
                break;
            default:
                break;
        }
    }

    @Override
    public void onReceivedMessageError(SocketConnection socketThread, Exception e) {
        for(MessageHandler item:messageHandlerList){
            item.onReceivedMessageError(socketThread,e);
        }
    }

    public class MyBinder extends Binder {
        public GalleryService getService(){
            return GalleryService.this;
        }
    }

    public String getIp(){
        WifiManager wm=(WifiManager)this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //检查Wifi状态
        if(!wm.isWifiEnabled())
            wm.setWifiEnabled(true);
        WifiInfo wi=wm.getConnectionInfo();
        //获取32位整型IP地址
        int ipAdd=wi.getIpAddress();
        //把整型地址转换成“*.*.*.*”地址
        String ip=intToIp(ipAdd);
        return ip;
    }
    public String intToIp(int i) {
        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }

    private void doLogin(SocketConnection socketThread, IMessage message){
        UserLoginMessage loginMessage=(UserLoginMessage)message;
        String password = sharedPreferences.getString("password", "");
        if(loginMessage.getLoginPassword()!=null&&loginMessage.getLoginPassword().trim().equals(password)){
            UserInfo userInfo=new UserInfo();
            userInfo.setLogin_name(loginMessage.getLoginName());
            User user=socketConnectionMap.get(socketThread);
            if(user==null){
                user=new User();
                socketConnectionMap.put(socketThread,user);
            }
            user.setLogin(true);
            user.setUserInfo(userInfo);
            user.setSessionId(MD5Util.MD5(System.currentTimeMillis()+""));
            MsgMessage msgMessage=new MsgMessage();
            msgMessage.setRespMessageId(message.getMessageId());
            msgMessage.setMessageType(MessageType.SUCCESS);
            msgMessage.setReceiver(message.getSender());
            msgMessage.setSender(message.getReceiver());
            msgMessage.setClientType(1);
            msgMessage.setDeviceSessionId(user.getSessionId());
            msgMessage.setMsg("登陆成功！");
            try {
                ServerConnectionManager.getInstance().sendMessageAndWaitResponse(msgMessage);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else{
            MsgMessage loginFailMessage=new MsgMessage();
            loginFailMessage.setMessageType(MessageType.ERROR);
            loginFailMessage.setRespMessageId(message.getMessageId());
            loginFailMessage.setClientType(1);
            loginFailMessage.setReceiver(message.getSender());
            loginFailMessage.setSender(message.getReceiver());
            loginFailMessage.setMsg("密码错误！");
            try {
                socketThread.sendMessage(loginFailMessage);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void doImage(SocketConnection socketThread, IMessage message){
        ImageMessage imageMessage=(ImageMessage)message;
        String file= Constant.IMAGE_PATH+imageMessage.getFileName();
        MsgMessage msgMessage=new MsgMessage(MessageType.SUCCESS,"保存成功："+file);
        msgMessage.setSender(message.getReceiver());
        msgMessage.setReceiver(message.getSender());
        msgMessage.setClientType(1);
        msgMessage.setRespMessageId(message.getMessageId());
        try {
            FileUtils.write(imageMessage.getImageBytes(), new File(file));
        }catch (Exception e){
            msgMessage.setMessageType(MessageType.ERROR);
            msgMessage.setMsg("保存失败："+e.getMessage());
        }
        try {
            socketThread.sendMessage(msgMessage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class  ConnectServerThread implements Runnable{

        @Override
        public void run() {
            try {
                DeviceInfo deviceInfo = new DeviceInfo();
                deviceInfo.setLocalIP(getIp());
                deviceInfo.setLocalPort(port);
                String serialNumber = android.os.Build.SERIAL;
                deviceInfo.setDeviceId(serialNumber);
                MsgMessage msgMessage = ServerConnectionManager.getInstance().connectServer(deviceInfo);
                if (ServerConnectionManager.getInstance().getSessionId() == null) {
                    if (msgMessage == null) {
                        sendHandlerMessage(2, "注册出错，请确定检查是否正常!");
                    } else if (msgMessage.getMessageType() == MessageType.SUCCESS) {
                        sendHandlerMessage(1, "注册成功！");
                        ServerConnectionManager.getInstance().startTestThread();
                    } else {
                        sendHandlerMessage(2, "注册失败!" + (msgMessage == null ? "" : msgMessage.getMsg()));
                    }
                }
                if (msgMessage != null && msgMessage.getMessageType() == MessageType.SUCCESS) {
                    ServerConnectionManager.getInstance().setSessionId(msgMessage.getSessionId());
                    ServerConnectionManager.getInstance().addMessageHandler(GalleryService.this);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    Toast.makeText(GalleryService.this, (String)msg.obj, Toast.LENGTH_LONG).show();

                    break;
                case 2:
                    Toast.makeText(GalleryService.this, (String)msg.obj, Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };
    public void sendHandlerMessage(int what,Object obj){
        Message msg=new Message();
        msg.what=what;
        msg.obj=obj;
        handler.sendMessage(msg);
    }

    private boolean checkPermission(User user,IMessage message){
        switch (message.getMessageType()){
            case IMAGE:
                if(user==null||user.getSessionId()==null||message.getDeviceSessionId()==null||!message.getDeviceSessionId().equals(user.getSessionId())){
                    return false;
                }
                break;
            default:
                 return true;
        }
        return true;
    }
}
